package org.xt.service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.jsoup.Connection;
import org.jsoup.Connection.Method;
import org.jsoup.Connection.Response;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.nutz.http.Cookie;
import org.nutz.http.Header;
import org.nutz.http.Request;
import org.nutz.http.Request.METHOD;
import org.nutz.http.Sender;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.util.NutMap;
/**
 * SFIS系统操作服务类
 * @author XiangTao
 *
 */
@IocBean
public class SFISOpService {
	/**
	 * 登录SFIS系统的cookie
	 */
	public static Map<String, String> ck = null;
	/**
	 * 获取cookeis
	 * @return cookies的map对象
	 */
	public Map<String, String> getCookies() {
		int sum = 0;
		while(ck == null && sum < 10){
			ck = login("S11050935", "wss521128");
			sum ++;
		}
		return ck;
	}
	/**
	 * 设置cookie
	 * @throws IOException
	 */
	public void setCookies() throws IOException {
		String url = "http://sfisweb3.sz.pegatroncorp.com/HermesWeb/SFISQuery/ISNQuery/ISNSummary/ISNSummary1.aspx";
		int sum = 0;
		while(sum < 10){
			ck = null;
			ck = login("S11050935", "wss521128");
			Connection connection = Jsoup.connect(url).method(Connection.Method.GET).cookies(ck).timeout(5 * 60 * 1000);
			conAddCommonHeader(connection);
			connection.header("Content-Type", "text/html; charset=utf-8");
			Response resp = connection.execute();
			String str = resp.body();
			if(!(str.contains("Login SFIS Web System"))){
				break;
			}
			sum ++;
		}
	}
	
	/**
	 * 登录 SFIS系统
	 * @param no 工号
	 * @param password 密码
	 * @return 登录获取的cookie MAP对象
	 */
	
	public Map<String, String> login(String no, String password) {
		//
		String loginUrl =  "http://sfisweb3.sz.pegatroncorp.com/HermesWeb/login.aspx";
		Connection connection = null;
		// 用get请求去获取表单数
		Map<String, String> datas = new HashMap<>();
		try {
			connection = Jsoup.connect(loginUrl).method(Connection.Method.GET).timeout(5 * 60 * 1000);
			conAddCommonHeader(connection);
			connection.header("Content-Type", "text/html; charset=utf-8");
			Connection.Response response = connection.execute();// 获取响应
			Document doc = Jsoup.parse(response.body());// 转换为Dom
			// map存放post时的数据
			String __VIEWSTATE = doc.getElementById("__VIEWSTATE").val();
			String __EVENTVALIDATION = doc.getElementById("__EVENTVALIDATION").val();
			datas.put("__EVENTTARGET", "");
			datas.put("__EVENTARGUMENT", "");
			datas.put("__VIEWSTATE", __VIEWSTATE);
			datas.put("__EVENTVALIDATION", __EVENTVALIDATION);
			datas.put("Login1:_ctl0:userID", no);
			datas.put("Login1:_ctl0:password", password);
			datas.put("Login1:_ctl0:autoLogin", "on");
			datas.put("Login1:_ctl0:loginButton", "Login");
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		
		connection = Jsoup.connect(loginUrl).method(Connection.Method.POST).data(datas).timeout(5 * 60 * 1000);
		conAddCommonHeader(connection);
		connection.header("Content-Type", "application/x-www-form-urlencoded");
		Map<String, String> cookies = new HashMap<>();
		try {
			Connection.Response rs;
			rs = connection.execute();
			if (rs.cookies() != null) {
				cookies = rs.cookies();
				return cookies;
			} else {
				return null;
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return null;
	}
	
	private void conAddCommonHeader(Connection connection) {
		connection.header("User-Agent",
				"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36");// 配置模拟浏览�?
		connection.header("Accept",
				"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8");
		connection.header("Accept-Encoding", "gzip, deflate");
		connection.header("Accept-Language", "zh-CN,zh;q=0.9");
		connection.header("Connection", "keep-alive");
		//connection.header(k, v);
	}
	/**
	 * 根据SN获取料号
	 * @param sn
	 * @return 料号
	 * @throws IOException
	 */
	public String getLiaohao(String sn) throws IOException{
		String url = "http://sfisweb3.sz.pegatroncorp.com/HermesWeb/SFISQuery/ISNQuery/ISNSummary/ISNSummary1.aspx";
		Connection con = Jsoup.connect(url).method(Connection.Method.GET).cookies(ck).timeout(5 * 60 * 1000);
		conAddCommonHeader(con);
		con.header("Content-Type", "text/html; charset=utf-8");
		Connection.Response resp = con.execute();// 获取响应
		Document doc = Jsoup.parse(resp.body());// 转换为Dom
		// map存放post时的数据
		String __VIEWSTATE = doc.getElementById("__VIEWSTATE").val();
		String __EVENTVALIDATION = doc.getElementById("__EVENTVALIDATION").val();
		Map<String, String> datas = new HashMap<>();
		datas.put("__VIEWSTATE", __VIEWSTATE);
		datas.put("__EVENTVALIDATION", __EVENTVALIDATION);
		datas.put("ISN", "rbtnSN");
		datas.put("txtISN", sn);
		datas.put("BtnMO_D", "MO_D");
		
		con = Jsoup.connect(url).method(Connection.Method.POST).data(datas).cookies(ck).timeout(5 * 60 * 1000);
		conAddCommonHeader(con);
		con.header("Content-Type", "application/x-www-form-urlencoded");
		try {
			Connection.Response rs;
			rs = con.execute();
			doc = Jsoup.parse(rs.body());
			Element ele = doc.getElementById("DataGridUP").getElementsByClass("columnItem").get(0).getElementsByTag("td").get(23);
			return ele.html();
		}catch(Exception e){
			e.printStackTrace();
		}
		return "";
	}
	
	/**
	 * 根据SN获取ArmChangeKPQuery
	 * @param sn
	 * @return 料号
	 * @throws IOException
	 */
	public String getArmChangeKPQuery(String sn) throws IOException{
		String url = "http://sfisweb3.sz.pegatroncorp.com/HermesWeb/SFISQuery/KoreQuery/ArmChangeKPQuery/ArmChangeKPQuery.aspx";
		Connection con = Jsoup.connect(url).method(Connection.Method.GET).cookies(ck).timeout(5 * 60 * 1000);
		conAddCommonHeader(con);
		con.header("Content-Type", "text/html; charset=utf-8");
		Connection.Response resp = con.execute();// 获取响应
		Document doc = Jsoup.parse(resp.body());// 转换为Dom
		// map存放post时的数据
		String __VIEWSTATE = doc.getElementById("__VIEWSTATE").val();
		String __EVENTVALIDATION = doc.getElementById("__EVENTVALIDATION").val();
		
		Request req = Request.create(url, METHOD.POST);
		Cookie cookie = new Cookie();
		Set<String> keys = ck.keySet();
		Iterator<String> it = keys.iterator();
		while(it.hasNext()){
			String key = it.next();
			cookie.set(key, ck.get(key));
		}
		req.setCookie(cookie);
		Map<String, String> map = new HashMap<>();
		map.put("User-Agent",
				"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36");// 配置模拟浏览�?
		map.put("Accept",
				"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8");
		map.put("Accept-Encoding", "gzip, deflate");
		map.put("Accept-Language", "zh-CN,zh;q=0.9");
		map.put("Connection", "keep-alive");
		map.put("Content-Type", "multipart/form-data; boundary=----WebKitFormBoundaryJqj5MgLePXlResKx");
		req.setHeader(Header.create(map));
		//靠 我说当初为啥获取不到，居然要在每一行后面加一个\r\n
		String str = "------WebKitFormBoundaryJqj5MgLePXlResKx\r\n";
		str += "Content-Disposition: form-data; name=\"__EVENTTARGET\"\r\n";
		str += "\r\n"; //握日 空白一行也要加
		str += "\r\n";
		str += "------WebKitFormBoundaryJqj5MgLePXlResKx\r\n";
		str += "Content-Disposition: form-data; name=\"__EVENTARGUMENT\"\r\n";
		str += "\r\n";
		str += "\r\n";
		str += "------WebKitFormBoundaryJqj5MgLePXlResKx\r\n";
		str += "Content-Disposition: form-data; name=\"__VIEWSTATE\"\r\n";
		str += "\r\n";
		str += __VIEWSTATE + "\r\n";
		str += "------WebKitFormBoundaryJqj5MgLePXlResKx\r\n";
		str += "Content-Disposition: form-data; name=\"__EVENTVALIDATION\"\r\n";
		str += "\r\n";
		str += __EVENTVALIDATION + "\r\n";
		str += "------WebKitFormBoundaryJqj5MgLePXlResKx\r\n";
		str += "Content-Disposition: form-data; name=\"tbKPSN\"\r\n";
		str += "\r\n";
		str += sn + "\r\n";
		str += "------WebKitFormBoundaryJqj5MgLePXlResKx\r\n";
		str += "Content-Disposition: form-data; name=\"FileImport\"; filename=\"\"\r\n";
		str += "Content-Type: application/octet-stream\r\n";
		str += "\r\n";
		str += "\r\n";
		str += "------WebKitFormBoundaryJqj5MgLePXlResKx\r\n";
		str += "Content-Disposition: form-data; name=\"btnQuery.x\"\r\n";
		str += "\r\n";
		str += "34\r\n";
		str += "------WebKitFormBoundaryJqj5MgLePXlResKx\r\n";
		str += "Content-Disposition: form-data; name=\"btnQuery.y\"\r\n";
		str += "\r\n";
		str += "3\r\n";
		str += "------WebKitFormBoundaryJqj5MgLePXlResKx--\r\n";
		req.setData(str);
		
		Sender s = Sender.create(req);
		s.setInterceptor(cookie);
		try {
			Connection.Response rs;
			rs = con.execute();
			return s.send().getContent();
		}catch(Exception e){
			e.printStackTrace();
		}
		return "";
	}
	
	/**
	 * 根据SN获取料号
	 * @param sn
	 * @return 料号
	 * @throws IOException
	 */
	public List<NutMap> getSNListByMo(String mo, String grp) throws IOException{
		String url = "http://sfisweb3.sz.pegatroncorp.com/HermesWeb/SFISQuery/showsfis/showisn.aspx?shop=&isn=&pre=&isnfrom=&isnto=&mo="+mo+"&grp="+grp+"&status=0";
		Connection con = Jsoup.connect(url).method(Connection.Method.GET).cookies(ck).timeout(5 * 60 * 1000);
		conAddCommonHeader(con);
		con.header("Content-Type", "text/html; charset=utf-8");
		Connection.Response resp = con.execute();// 获取响应
		Document doc = Jsoup.parse(resp.body());// 转换为Dom
		Elements eles = doc.getElementById("DataGrid1")
				.getElementsByTag("tbody").get(0)
				.getElementsByTag("tr");
		List<NutMap> res = new ArrayList<>();
		for(int i = 2; i <eles.size(); i ++){
			Element ele = eles.get(i);
			NutMap re = NutMap.NEW();
			try{
				String sn = ele.getElementsByTag("td").get(2).html();
				re.addv("sn", sn);
			}catch(Exception e){
				
			}
			try{
				String WIP = ele.getElementsByTag("td").get(3).html();
				re.addv("WIP", WIP);
			}catch(Exception e){
				
			}
			try{
				String W90 = ele.getElementsByTag("td").get(4).html();
				re.addv("W90", W90);
			}catch(Exception e){
				
			}
			res.add(re);
		}
		return res;
	}
}
